<template>
    <div>
        <div class="search-term">
            <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                <el-form-item>
                    <el-input
                            placeholder="请输入账户名称"
                            v-model="searchInfo.accountName"
                            clearable
                            size="small"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="status">
                    <el-select
                            v-model="searchInfo.roleId"
                            placeholder="请选择角色"
                            clearable
                            size="small"
                    >
                        <el-option
                                v-for="item in roleOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" type="primary" size="small"
                    >搜 索
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="openDialog('add')" size="small" v-if="btns&&btns.includes('add')">新 增</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="tableData" style="width: 100%;margin-bottom: 10px;" border>
            <el-table-column prop="username" label="账户名称" align="center">
            </el-table-column>
            <el-table-column prop="roleName" label="角色" align="center">
            </el-table-column>
            <el-table-column prop="areaName" label="区域" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" align="center">
            </el-table-column>
            <el-table-column prop="enabled" label="状态" align="center">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.enabled" :active-value=1 :inactive-value=0
                               @change="changeEnable(scope.row)" style="padding-right:15px">
                    </el-switch>
                    <span :class="scope.row.enabled === 1 ? 'green' : 'red'">{{scope.row.enabled === 1 ? "启用" : "停用"}}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="230px">
                <template slot-scope="scope">
                    <el-button
                            @click="editArea(scope.row)"
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                            v-if="btns&&btns.includes('edit')"
                    >编辑
                    </el-button>
                    <el-button
                            @click="resetPwd(scope.row)"
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                    >重置密码
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="currPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                :style="{ float: 'right', padding: '20px' }"
                :total="totalCount"
                @current-change="handlepageChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>

        <el-dialog
                :before-close="closeDialog"
                :title="dialogTitle"
                :visible.sync="dialogFormVisible"
                class="dialogs"
        >
            <el-form
                    :model="form"
                    :inline="true"
                    :rules="rules"
                    label-width="80px"
                    ref="areaForm"
            >
                <el-divider content-position="left">基本信息</el-divider>
                <el-form-item label="头像" prop="headImgUrl" class="pics">
                    <el-upload
                            class="avatar-uploader"
                            :action="`${path}/api-system/file/upload/account`"
                            list-type="picture-card"
                            :show-file-list="false"
                            :before-upload="checkFile"
                            :headers="{ Authorization: token }"
                            :on-error="uploadError"
                            :on-success="uploadSuccess"
                    >
                        <div class="header-background">
                            <img v-if="isShowImg" :src="form.headImgUrl" class="avatar" width="100%" height="100%"/>
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select
                            v-model="form.roleId"
                            placeholder="请选择角色"
                            size="small"
                            :disabled="mobileFlag"
                            clearable
                            @change="roleChange"
                    >
                        <el-option
                                v-for="item in roleOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="账户名称" prop="username" style="margin-right: 120px">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            :disabled="mobileFlag"
                            placeholder="请输入账户名称"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex" >
                    <el-radio-group v-model="form.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="添加学生方式" prop="sex"  class="item-label" v-if="form.roleId === 4">
                    <el-radio-group v-model="form.userExtendVO.addStuType">
                        <el-radio :label="0">学校PC端添加</el-radio>
                        <el-radio :label="1">家长APP端添加</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-divider content-position="left">地址信息</el-divider>
                <el-form-item label="区域" prop="areaId">
                    <div style="width: 230px;" v-if="options">
                        <treeselect
                                placeholder="选择区域"
                                :options="options"
                                noResultsText="未查询到该地区"
                                noChildrenText="无下级区域"
                                v-model="selectValue"
                                :valueFormat="selectValueFormat"
                                loadingText="疯狂加载中..."
                                openDirection="auto"
                                :load-options="loadOptions"
                                @select="getAreaInfo"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input
                            autocomplete="off"
                            v-model="form.address"
                            size="small"
                            placeholder="详细地址"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input
                            autocomplete="off"
                            v-model="form.mobile"
                            size="small"
                            placeholder="请输入手机号"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-divider content-position="left" v-if="form.roleId === 3||form.roleId === 4"
                >结算信息
                </el-divider
                >
                <el-form-item label="结算方式" prop="userExtendVO.settlementType"
                              v-if="form.roleId === 3||form.roleId === 4">
                    <el-radio-group v-model="form.userExtendVO.settlementType" @change="settlementTypeChange">
                        <el-radio :label="0">固定金额</el-radio>
                        <el-radio :label="1">比例结算</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="结算金额" prop="userExtendVO.settlementMoney"
                              v-if="(form.roleId === 3||form.roleId === 4)&&form.userExtendVO.settlementType===0">
                    <el-input
                            autocomplete="off"
                            v-model="form.userExtendVO.settlementMoney"
                            size="small"
                            placeholder="结算金额"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            clearable
                    >
                        <template slot="append">元/课时</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="结算比例" prop="userExtendVO.settlementRatio"
                              v-if="(form.roleId === 3||form.roleId === 4)&&form.userExtendVO.settlementType===1">
                    <el-input
                            autocomplete="off"
                            v-model="form.userExtendVO.settlementRatio"
                            size="small"
                            placeholder="结算比例"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            clearable
                    >
                        <template slot="append"> %</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="银行卡号" prop="userExtendVO.bankAccount" v-if="form.roleId === 3||form.roleId === 4">
                    <el-input
                            autocomplete="off"
                            v-model="form.userExtendVO.bankAccount"
                            size="small"
                            placeholder="银行卡号"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="银行户名" prop="userExtendVO.bankUserName" v-if="form.roleId === 3||form.roleId === 4">
                    <el-input
                            autocomplete="off"
                            v-model="form.userExtendVO.bankUserName"
                            size="small"
                            placeholder="银行户名"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="开户行" prop="userExtendVO.bankOpen" v-if="form.roleId === 3||form.roleId === 4">
                    <el-input
                            autocomplete="off"
                            v-model="form.userExtendVO.bankOpen"
                            size="small"
                            placeholder="开户行"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-divider content-position="left" v-if="form.roleId === 3"
                >备注
                </el-divider
                >
                <el-form-item label="  " prop="remarks" v-if="form.roleId === 3">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.remarks"></el-input>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button @click="enterDialog" type="primary" size="small"
                >确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    // 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
    import {mapGetters} from "vuex";
    import {areaList, loadChildData} from "@/api/api";
    import {addUser, editUser, enableAccount, resetPwd, userDetail, userList} from "@/api/account";
    import infoList from "@/components/mixins/infoList";
    import Treeselect, {LOAD_CHILDREN_OPTIONS} from '@riophae/vue-treeselect'

    // We just use `setTimeout()` here to simulate an async operation
    // instead of requesting a real API server for demo purpose.
    export default {
        components: {Treeselect},
        name: "account",
        mixins: [infoList],
        data() {
            const checkPassword = (rule, value, callback) => {
                if (value.length < 6 || value.length > 20) {
                    return callback(new Error("请输入6~20个字符"));
                } else {
                    callback();
                }
            };
            const checkPhone = (rule, value, callback) => {
                const reg = /^1[3456789]\d{9}$/;
                if (!reg.test(value)) {
                    callback(new Error("请输入正确的手机号码"));
                } else {
                    callback();
                }
            };
            return {
                saveFlag: true,
                mobileFlag: false,
                arrayTempFirst: [],
                arrayTemp: [],
                selectValue: null,
                selectValueFormat: "",
                options: [],
                isShowImg: false,
                btns: [],
                props: {
                    lazy: true,
                    value: "areaId",
                    label: "name"
                },
                path: process.env.VUE_APP_BASE_API,
                sexOptions: [
                    {
                        value: 0,
                        label: "女",
                    },
                    {
                        value: 1,
                        label: "男",
                    },
                ],
                settlementTypeOptions: [{
                    value: 0,
                    label: "固定",
                }, {
                    value: 0,
                    label: "比例",
                }],
                statusOptions: [
                    {
                        value: 0,
                        label: "否",
                    },
                    {
                        value: 1,
                        label: "是",
                    },
                ],
                roleOptions: [],
                listApi: userList,
                searchInfo: {currentAreaId: 0, currentRoleId: 0},
                dialogFormVisible: false,
                dialogTitle: "新增账户",
                form: {
                    userExtendVO: {
                        settlementType: 0,
                        settlementMoney: 0,
                        settlementRatio: 0,
                        bankAccount: '',
                        bankUserName: '',
                        bankOpen: ''
                    }
                },
                type: "",
                rules: {
                    username: [{required: true, message: "请输入账户名称", trigger: "blur"},],
                    roleId: [{required: true, message: "请选择角色", trigger: "change"}],
                    areaId: [{required: true, message: "请选择区域", trigger: "change"}],
                    sex: [{required: true, message: "请选择性别", trigger: "change"}],
                    mobile: [{required: true, message: "请输入手机号", trigger: "blur"}, {
                        validator: checkPhone,
                        trigger: "blur"
                    },],
                    password: [
                        {required: true, message: "请输入密码", trigger: "blur"},
                        {validator: checkPassword, trigger: "blur"},
                    ],
                },
                parentId: 0,
            };
        },
        computed: {
            ...mapGetters("user", ["userInfo", "token"]),
        },
        methods: {
            async getAreaInfo(node, instanceId) {
                this.form.areaId = node.id;
                this.form.areaName = node.label;
            },
            async handleItemChange(val) {
                const res = await loadChildData()
            },
            checkFile(file) {
                this.saveFlag = false;
                this.isShowImg = false;
                this.form.headImgUrl = '';
                this.fullscreenLoading = true;
                const isJPG = file.type === "image/jpeg";
                const isPng = file.type === "image/png";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG && !isPng) {
                    this.$message.error("上传头像图片只能是 JPG或png 格式!");
                    this.fullscreenLoading = false;
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                    this.fullscreenLoading = false;
                }
                return (isPng || isJPG) && isLt2M;
            },
            //选择学校/机构的时候结算必填
            roleChange(val) {
                if (val === 3 || val === 4) {
                    this.rules = Object.assign(this.rules, {
                        'userExtendVO.settlementType': [{required: true, message: "请选择结算方式", trigger: "change"}]
                    })
                } else {
                    this.$refs.areaForm.clearValidate('userExtendVO.settlementType');
                }
            },
            settlementTypeChange(val) {
                if (val === 0) {
                    this.form.userExtendVO.settlementRatio = 0
                }
                if (val === 1) {
                    this.form.userExtendVO.settlementMoney = 0;
                }
            },
            uploadSuccess(res, file) {
                this.fullscreenLoading = false;
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "上传成功",
                    });
                    this.saveFlag = true;
                    this.isShowImg = true;
                    this.form.headImgUrl = res.data;
                } else {
                    this.$message({
                        type: "warning",
                        message: res.msg,
                    });
                }
            },
            uploadError() {
                this.$message({
                    type: "error",
                    message: "上传失败",
                });
                this.saveFlag = true;
                this.fullscreenLoading = false;
            },
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1;
                this.pageSize = 10;
                this.getTableData();
            },
            initForm() {
                this.$refs.areaForm.resetFields();
                this.isShowImg = false
            },
            closeDialog() {
                this.initForm();
                this.dialogFormVisible = false;
            },
            openDialog(type) {
                switch (type) {
                    case "add":
                        this.selectValue = null;
                        this.mobileFlag = false;
                        this.dialogTitle = "新增账户";
                        break;
                    case "edit":
                        this.dialogTitle = "编辑账户";
                        this.mobileFlag = true;
                        break;
                    default:
                        break;
                }
                this.type = type;
                this.dialogFormVisible = true;
            },
            //重置密码
            async resetPwd(row) {
                this.$confirm("此操作将密码重置为手机号码, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        const res = await resetPwd(row.userId);
                        if (res.statusCode === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消",
                        });
                    });
            },
            //启用/停用
            async changeEnable(row) {
                const res = await enableAccount(row.userId)
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "启用/停用成功",
                        showClose: true,
                    });
                }
                this.getTableData();
            },
            async editArea(row) {
                const res = await userDetail(row.userId, 0);
                this.form = res.data;
                if (this.form.userExtendVO === undefined) {
                    this.form = Object.assign(this.form, {
                        userExtendVO: {
                            settlementType: 0,
                            settlementMoney: 0,
                            settlementRatio: 0,
                            bankAccount: '',
                            bankUserName: '',
                            bankOpen: ''
                        }
                    });
                }
                if (this.form.headImgUrl !== '') {
                    this.isShowImg = true;
                }
                this.selectValue = {id: res.data.areaId, label: res.data.areaName, children: null};
                this.selectValueFormat = res.data.areaName
                this.openDialog("edit");

            },
            async deleteAreas(row) {
                this.$confirm("此操作将永久删除该地区, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        const res = await deleteArea(row.userId);
                        if (res.statusCode === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            },
            async loadOptions({action, parentNode, callback}) {
                if (action === LOAD_CHILDREN_OPTIONS) {
                    //点击选项事件
                    const res = await areaList(1, parentNode.id, 1)
                    res.data.forEach((item, index, array) => {
                        if (item.childNumber > 0) {
                            this.arrayTemp.push({
                                id: item.areaId,
                                label: item.shortName,
                                children: null
                            });
                        } else {
                            this.arrayTemp.push({
                                id: item.areaId,
                                label: item.shortName,
                                children: undefined
                            });
                        }
                    })
                    parentNode.children = this.arrayTemp;
                    this.arrayTemp = [];
                    callback()
                }
            },
            async enterDialog() {
                this.$refs.areaForm.validate(async (valid) => {
                    if (valid) {
                        switch (this.type) {
                            case "add": {
                                const res = await addUser(this.form);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "添加成功",
                                        showClose: true,
                                    });
                                    this.getTableData();
                                    this.closeDialog();
                                }
                            }
                                break;
                            case "edit": {
                                const res = await editUser(this.form);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "编辑成功",
                                        showClose: true,
                                    });
                                    this.getTableData();
                                    this.closeDialog();
                                }
                            }
                                break;
                            default: {
                                this.$message({
                                    type: "error",
                                    message: "未知操作",
                                    showClose: true,
                                });
                            }
                                break;
                        }
                    }
                });
            },
        },
        async created() {
            if (this.userInfo.roleId === 1) {
                this.roleOptions = [{
                    value: 3,
                    label: "机构",
                },
                    {
                        value: 4,
                        label: "学校",
                    },
                    {
                        value: 5,
                        label: "教育局",
                    },
                    {
                        value: 2,
                        label: "运营人员",
                    },
                    {
                        value: 1,
                        label: "超级管理员",
                    },
                    {
                        value: 6,
                        label: "财务",
                    }]
            }
            if (this.userInfo.roleId === 2) {
                this.roleOptions = [{
                    value: 3,
                    label: "机构",
                },
                    {
                        value: 4,
                        label: "学校",
                    },
                    {
                        value: 5,
                        label: "教育局",
                    },
                    {
                        value: 2,
                        label: "运营人员",
                    }]
            }
            this.options = [];
            this.searchInfo.currentAreaId = this.userInfo.areaId;
            this.searchInfo.currentRoleId = this.userInfo.roleId;
            this.getTableData();
            this.btns = this.$route.meta.btnList;
            const res = await areaList(1, this.userInfo.areaId, 0)
            //this.cascaderData = res.data
            res.data.forEach((item, index, array) => {
                if (item.childNumber > 0) {
                    this.arrayTempFirst.push({
                        id: item.areaId,
                        label: item.shortName,
                        children: null
                    })
                } else {
                    this.arrayTempFirst.push({
                        id: item.areaId,
                        label: item.shortName,
                        children: undefined
                    })
                }
            })
            this.options = this.arrayTempFirst;
        },
    };
</script>
<style scoped lang="scss">
    .green {
        color: #67c23a;
    }

    .red {
        color: #f56c6c;
    }

    .button-box {
        // padding: 10px 20px;
        .el-button {
            float: right;
        }
    }

    .el-tag--mini {
        margin-left: 5px;
    }

    .dialogs {
        ::v-deep .el-dialog{
            width: 40%;
        }
        ::v-deep .el-input-group--append .el-input__inner {
            width: 170px !important;
        }

        ::v-deep .el-dialog__body {
            padding: 15px 20px 10px 20px;
        }

        /*::v-deep .el-input__inner {*/
        /*    width: 225px;*/
        /*}*/

        ::v-deep .el-textarea__inner {
            width: 450px;
        }

        .dialog-footer {
            text-align: center;
        }

        ::v-deep .el-input-number .el-input__inner {
            width: 130px;
        }

        ::v-deep .el-form .pics {
            width: 100%;
            margin-bottom: 22px;
        }

        ::v-deep .el-form .el-divider .el-divider__text {
            font-weight: bold;
            color: #409eff;
        }

        .item-label {
            ::v-deep .el-form-item__label {
                width: 110px !important;
            }

            ::v-deep .el-input__inner {
                width: 162px;
            }
        }
    }

    .header-background {
        position: absolute;
        width: 146px;
        height: 146px;
    }

    @import '../../style/punch-treeselect.css';
</style>
